package com.dly.blog.domain.ro;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.db.sql.Direction;
import cn.hutool.db.sql.Order;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;

import java.util.List;
import java.util.Objects;

/**
 * @Author: DaiLiYu
 * @Date: 2023/7/21 10:30
 */
@Data
public class PageRO {

    @Schema(description = "页面大小")
    private int size;

    @Schema(description = "当前第几页")
    private int current;

    @Schema(description = "排序相关字段", example = "{direction: 'DESC', field:'id'}")
    private List<Order> orders;

    public <T> Page<T> buildIPage() {
        Page<T> of = Page.of(this.current, this.size);
        if (ObjectUtil.isNotNull(orders)) {
            List<OrderItem> orderItems = orders.stream().map(order ->
                    switch (order.getDirection()) {
                        case DESC -> OrderItem.desc(order.getField());
                        default -> OrderItem.asc(order.getField());
                    }).toList();
            of.addOrder(orderItems);
        }
        return of;
    }

    public PageRequest buildPageRequest() {
        if (ObjectUtil.isNotNull(orders)) {
            List<Sort.Order> orderList = orders.stream().map(order ->
                    switch (order.getDirection()) {
                        case DESC -> Sort.Order.desc(order.getField());
                        default -> Sort.Order.asc(order.getField());
                    }
            ).toList();
            return PageRequest.of(current - 1, size, Sort.by(orderList));
        }
        return PageRequest.of(current - 1, size);
    }
}
